//
//  PictureSelectorViewController.swift
//  照片选择器
//
//  Created by ZhangChao on 15/9/10.
//  Copyright © 2015年 ZhangChao. All rights reserved.
//

import UIKit

private let PictureSelectorCellID = "PictureSelectorCellID"

// 最大图片数量
private let PictureMaxCount = 9

class PictureSelectorViewController: UICollectionViewController ,PictureSelectorCellDelegate{
    
    // 定义一个图片数组
    private lazy var pictures = [UIImage]()
    
    // 定义一个属性记录当前选中cell的indexPath
    private var currentIndex = 0
    
    // 在构造方法中设置流布局
    init(){
        let layout = UICollectionViewFlowLayout()
        
        super.init(collectionViewLayout: layout)
        
        // 设置布局
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Register cell classes
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: PictureSelectorCellID)
        
        collectionView?.backgroundColor = UIColor(white: 0.97, alpha: 1.0)
    }

    // MARK: - UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        // 这里的+1是让视图显示一张图片
        return pictures.count + (pictures.count == PictureMaxCount ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureSelectorCellID, forIndexPath: indexPath) as! PictureSelectorCell
    
//        cell.backgroundColor  = UIColor.redColor()
        
        //遵守代理
        cell.pictureDelegate = self
        
        // 设置cell的图片
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
        
        return cell
    }

    // MARK: - UICollectionViewDelegate
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        /// Camera              相机
        /// PhotoLibrary        照片库 － 包含相册，包括通过 iTunes / iPhoto 同步的照片，同步的照片不允许在手机删除
        /// SavedPhotosAlbum    相册 － 相机拍摄，应用程序保存的图片，可以删除
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
            
            return
        }
        
        let vc = UIImagePickerController()
        
        vc.delegate = self
        
        // 记录当前选中的cell的index
        currentIndex = indexPath.item
        
        // 编辑模式(进入编辑模式中可以编辑图像,在上传头像的时候非常有用)
//        vc.allowsEditing = true
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    // MARK: - 实现删除按钮的代理方法
    private func pictureSelectorCellRemoveBtnClick(cell: PictureSelectorCell){
//        print("shanchu")
        if let indexPath = collectionView?.indexPathForCell(cell) where indexPath.item < pictures.count {
            
            // 删除索引对应的图片
            pictures.removeAtIndex(indexPath.item)
            
        }
        // 刷新数据
        collectionView?.reloadData()
        
    }
  
}
// MARK: - 自定义代理,实现删除按钮的点击事件
private protocol PictureSelectorCellDelegate : NSObjectProtocol {
    
    func pictureSelectorCellRemoveBtnClick(cell:PictureSelectorCell)
    
}

// MARK: - 自定义cell
private class PictureSelectorCell : UICollectionViewCell{
    
    // 定义图片属性
    var image : UIImage?{
        didSet{
            // 判断有没有图片
            if image != nil {
                
                pictureBtn.setImage(image, forState: UIControlState.Normal)
                
            }else{
                
                pictureBtn.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            }
            // 没有图片的时候让删除按钮隐藏
            removeBtn.hidden = (image == nil)
        }
    }
    
    // 定义代理(注意weak属性)
    weak var pictureDelegate : PictureSelectorCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
///  调用代理方法
    @objc private func removeBtnClick(){
        
        pictureDelegate?.pictureSelectorCellRemoveBtnClick(self)
    }
    
    private func setupUI(){
        
        // 添加控件
        contentView.addSubview(pictureBtn)
        contentView.addSubview(removeBtn)
        
        // 自动布局
        pictureBtn.frame = bounds
        
        removeBtn.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[btn]-0-|", options: [], metrics: nil, views: ["btn":removeBtn]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[btn]", options: [], metrics: nil, views: ["btn":removeBtn]))
     
        // 禁用照片按钮的用户交互
        pictureBtn.userInteractionEnabled = false
        
        // 通过修改按钮的contentMode 才能修改按钮显示图片的方式
        pictureBtn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill
        
        // 给删除按钮添加点击事件
        removeBtn.addTarget(self, action: "removeBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    // 懒加载控件
    // 图片按钮
    private lazy var pictureBtn : UIButton = UIButton(imageName: "compose_pic_add")
    // 删除照片的按钮
    private lazy var removeBtn : UIButton = UIButton(imageName: "compose_photo_close")
    
}
// MARK: - UIImagePicker 的代理方法
extension PictureSelectorViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        // 用分类更改图片大小(解决内存暴涨的问题)
        let scaleImage = image.scalePictureToSize(300)
        
        // 如果点击的是已经有图片的cell 更换图片,而不是加到最后
        if currentIndex < pictures.count{
            
            pictures[currentIndex] = scaleImage
        
        }else{
            
            pictures.append(scaleImage)
        }
        
        // 刷新数据
        collectionView?.reloadData()
        
        // 实现了代理方法,控制器就不会自己消失了
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}